package edu.bbk.muc.lifetracker;

import edu.bbk.muc.lifetracker.common.Acceleration;
import edu.bbk.muc.lifetracker.common.Configuration;
import edu.bbk.muc.lifetracker.common.Event;
import edu.bbk.muc.lifetracker.common.GlobalEvent;
import edu.bbk.muc.lifetracker.common.SensorsToUi;
import edu.bbk.muc.lifetracker.common.SimpleLocation;

/**
 * Implements the logic of processing sensor events.
 * @author irenatyler and romankirillov
 */
public class SensorCallbackReceiver implements SensorsToUi {
  private Configuration configuration;
  private final EventReceiver eventReceiver;

  /**
   * Created from UI
   * 
   * @param configuration
   *          current (initial) configuration
   * @param receiver
   *          where events should be sent after being built
   */
  public SensorCallbackReceiver(Configuration configuration, EventReceiver receiver) {
    this.configuration = configuration;
    this.eventReceiver = receiver;

  }

  @Override
  public void onAccelerationChanged(long timestamp, Acceleration acceleration) {
    GlobalEvent.get().setAcceleration(timestamp, acceleration);
    checkAndDispatch();
  }

  @Override
  public void onAmbientLightChanged(long timestamp, float light) {
    GlobalEvent.get().setAmbientLight(timestamp, light);
    checkAndDispatch();
  }

  @Override
  public void onLocationChanged(long timestamp, SimpleLocation location) {
    GlobalEvent.get().setLocation(timestamp, location);
  }

  public void setConfiguration(Configuration config) {
    this.configuration = config;
  }

  private void checkAndDispatch() {
    final Event theEvent;
    if ((theEvent = GlobalEvent.get().buildEvent(configuration)) != null) {
      eventReceiver.onEventReady(theEvent);
    }
  }
}
